package com.gt.gt_securitytest.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gt.gt_securitytest.entity.MyUserDetails;
import com.gt.gt_securitytest.entity.Users;
import com.gt.gt_securitytest.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username",username);
        Users users = userMapper.selectOne(wrapper);
        if (users == null)
            throw new RuntimeException("用户不存在或已被禁用");

        MyUserDetails myUserDetails = new MyUserDetails();
        myUserDetails.setUsername(users.getUsername());
        myUserDetails.setPassword(users.getPassword());
        myUserDetails.setPhone(users.getPhone());


        List<String> list = new ArrayList<>();
        if ("gtboy".equals(username)){
            list.add("USER");
            list.add("ADMIN");
            myUserDetails.setRoles(list);
        }
        if ("fzh".equals(username)){
            list.add("USER");
            myUserDetails.setRoles(list);
        }
        return myUserDetails;
    }
}
